package com.ruoyi.wechat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.chat.domain.ChatLast;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.domain.entity.Member;
import com.ruoyi.common.core.domain.entity.StoreUser;
import com.ruoyi.common.core.domain.entity.StoreUserRole;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.member.service.IMemberService;
import com.ruoyi.memberSer.domain.MemberSer;
import com.ruoyi.memberSer.service.IMemberSerService;
import com.ruoyi.store.domain.StoreApply;
import com.ruoyi.store.service.IStoreUserRoleService;
import com.ruoyi.storeUser.service.IStoreUserService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.wechat.Miniprogram;
import com.ruoyi.wechat.Template;
import com.ruoyi.wechat.TemplateCode;
import com.ruoyi.wechat.TemplateParam;
import com.ruoyi.wechat.service.WeChatMessageService;
import com.ruoyi.wechat.util.TokenUtil;
import com.squareup.okhttp.Challenge;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.plaf.DesktopIconUI;
import java.util.ArrayList;
import java.util.List;
/**
 * @author chengliang
 * @date 2022/3/2
 **/
@Service
public class WeChatMessageServiceImpl implements WeChatMessageService {
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IStoreUserService userService;
    @Autowired
    private IMemberSerService serService;
    @Autowired
    private IStoreUserRoleService roleService;
    @Autowired
    private TokenUtil tokenUtil;
    private String getTemplateCode(){

        return tokenUtil.getToken("yqs").getAccessToken();
        /*String appId = sysConfigService.selectConfigByKey("yqs_APPKEY");
            String appSecret = sysConfigService.selectConfigByKey("yqs_SECRET");
            String beforeUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                    "&appid=" + appId +
                    "&secret="+appSecret;

            String content = HttpUtils.doGet(beforeUrl, "UTF-8", 100, 1000);
            JSONObject jsonObject = JSON.parseObject(content);
            if(jsonObject.get("access_token") != null){
                return jsonObject.getString("access_token");
            }
        return null;*/
    }
    @Override
    public void answer(ChatLast last) {
        try{
            Template template = new Template();
            template.setTemplate_id("uK-Rxxd6IyrP8mE2WhBa2qIGdU9XhYay8shyYhsLKAE");
            Long memberId=last.getMemberId();
            Member member= memberService.selectMemberById(memberId);
            MemberSer ser = serService.selectMemberSerByUinonId(member.getUnionId());
            if(null == ser){
                return;
            }
            template.setTouser(ser.getOpenId());
            template.setPage(TemplateCode.AGENT_INDEX);
            List<TemplateParam> params = new ArrayList<>();
            params.add(new TemplateParam("first","您有一条商家的新消息"));

            params.add(new TemplateParam("keyword1","问题反馈"));
            if(DicConstants.CHAT_TYPE_img.getCode().equals(last.getMsgType())){
                params.add(new TemplateParam("keyword2", "图片"));
            }else{
                params.add(new TemplateParam("keyword2", last.getContent()));
            }
            params.add(new TemplateParam("remark",""));
            template.setTemplateParamList(params);
            List<Miniprogram> miniprograms = new ArrayList<>();
            String app_id = sysConfigService.selectConfigByKey("app_id");

            miniprograms.add(new Miniprogram("appid",app_id));
            miniprograms.add(new Miniprogram("path","pages/home/home"));
            template.setMiniprogram(miniprograms);
            String token = getTemplateCode();
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
            String content = HttpUtils.sendPost(url, template.toJSON());
            System.out.println(content);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void tipMsg(Long userId, StoreApply apply) {
        try{
            Template template = new Template();
            template.setTemplate_id("SjRY9Uj3p9aPUlipvrN6Id4UA9BF_P3RDrzoPLSVqEI");

            StoreUser agentUser = userService.selectStoreUserById(userId);
            MemberSer ser = serService.selectMemberSerByUinonId(agentUser.getUnionId());
            if(null == ser){
                return;
            }
            template.setTouser(ser.getOpenId());
            //template.setPage(TemplateCode.AGENT_INDEX);
            List<TemplateParam> params = new ArrayList<>();
            params.add(new TemplateParam("first","门店入驻义枫美业审核通过"));
            params.add(new TemplateParam("keyword1",apply.getStoreName()));
            params.add(new TemplateParam("keyword2", DateUtils.dateToStr(apply.getUpdateTime())));
            params.add(new TemplateParam("remark","快去上架商品吧"));
            template.setTemplateParamList(params);
            List<Miniprogram> miniprograms = new ArrayList<>();
            String app_id = sysConfigService.selectConfigByKey("app_id_store");
            miniprograms.add(new Miniprogram("appid",app_id));
            miniprograms.add(new Miniprogram("path","pages/middlePage/middlePage"));
            template.setMiniprogram(miniprograms);

            String token = getTemplateCode();
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
            String content = HttpUtils.sendPost(url, template.toJSON());
            System.out.println(content);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @Override
    public void refuseMsg(Long userId, StoreApply apply) {
        try{
            Template template = new Template();
            template.setTemplate_id("3amC4mqVm0pNlQqglpHiBKQoDaUpwGMcjH-nuZ6nFjo");

            StoreUser agentUser = userService.selectStoreUserById(userId);
            MemberSer ser = serService.selectMemberSerByUinonId(agentUser.getUnionId());
            if(null == ser){
                return;
            }
            template.setTouser(ser.getOpenId());
            //template.setPage(TemplateCode.AGENT_INDEX);
            List<TemplateParam> params = new ArrayList<>();
            params.add(new TemplateParam("first","抱歉，门店资料审核未通过"));
            params.add(new TemplateParam("keyword1",apply.getStoreName()));
            params.add(new TemplateParam("keyword2", DateUtils.dateToStr(apply.getUpdateTime())));
            params.add(new TemplateParam("remark",apply.getRefuseMsg()));
            template.setTemplateParamList(params);
            List<Miniprogram> miniprograms = new ArrayList<>();
            String app_id = sysConfigService.selectConfigByKey("app_id_store");
            miniprograms.add(new Miniprogram("appid",app_id));
            miniprograms.add(new Miniprogram("path","pages/middlePage/middlePage"));
            template.setMiniprogram(miniprograms);

            String token = getTemplateCode();
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
            String content = HttpUtils.sendPost(url, template.toJSON());
            System.out.println(content);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void question(ChatLast last) {
        try{
            Template template = new Template();
            template.setTemplate_id("2fSJbm6ZJqpvoIYSinZxZxlIKOw_kkipRdsMk1y285s");

            Member member = memberService.selectMemberById(last.getMemberId());

            Long storeId=last.getStoreId();
            Long storeUserId=0L;
            StoreUserRole storeUserRolePara=new StoreUserRole();
            storeUserRolePara.setStoreId(storeId);
            List<StoreUserRole>  listStoreUserRole=roleService.selectStoreUserRoleList(storeUserRolePara);
            for (StoreUserRole su:listStoreUserRole) {
                if(DicConstants.STORE_Identity_Manager.getCode().equals(su.getRoleType())){
                    storeUserId=su.getStoreUserId();
                    break;
                }
            }
            StoreUser agentUser = userService.selectStoreUserById(storeUserId);
            MemberSer ser = serService.selectMemberSerByUinonId(agentUser.getUnionId());
            if(null == ser){
                return;
            }
            template.setTouser(ser.getOpenId());
            //template.setPage(TemplateCode.AGENT_INDEX);
            List<TemplateParam> params = new ArrayList<>();
            params.add(new TemplateParam("first","您有一条用户发来的新消息"));
            params.add(new TemplateParam("keyword1",member.getNickName()));
            params.add(new TemplateParam("keyword2",""));
            params.add(new TemplateParam("keyword3", DateUtils.dateToStr(last.getCreateTime())));
            params.add(new TemplateParam("keyword4","用户咨询"));
            if(DicConstants.CHAT_TYPE_img.getCode().equals(last.getMsgType())){
                params.add(new TemplateParam("keyword5","图片"));
            }else{
                params.add(new TemplateParam("keyword5",last.getContent()));
            }

            params.add(new TemplateParam("remark",""));
            template.setTemplateParamList(params);
            List<Miniprogram> miniprograms = new ArrayList<>();
            String app_id = sysConfigService.selectConfigByKey("app_id_store");
            miniprograms.add(new Miniprogram("appid",app_id));
            miniprograms.add(new Miniprogram("path","pages/middlePage/middlePage"));
            template.setMiniprogram(miniprograms);

            String token = getTemplateCode();
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
            String content = HttpUtils.sendPost(url, template.toJSON());
            System.out.println(content);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
